//认证详情

import React, { useState, useMemo, useRef, useEffect } from 'react';
import { Button, Alert, Popover, Radio, message } from 'antd';
import CommonModal from '@/components/CommonModal';
import CheckCellPhoneCodeModal from './CheckCellPhoneCodeModal';
import AddAuthentication from './AddAuthentication';
import ComfortableTipsModal from './ComfortableTipsModal';
import NewBindCardModal from './NewBindCardModal';
import CommonQinnvImgsLoad from './CommonQinnvImgsLoad';
import CommonLoading from '@/components/CommonLoading';
import { getAttestation, bankValidate, userOpenAccount } from './service.js';
import { IdCardDesensitization } from '@/utils/utils.jsx';
import styles from './index.module.less';

//用户类型map
const typeMap = {
  1: '个人',
  2: '企业',
  3: '企业',
};

const AttestationDetail = ({
  visible,
  isOpen,
  //   accountExtend,
  UpgradeEnterprise = false,
  userAccountType,
  handleCancel,
  handUpdataData,
  handleOk,
  handUpdateAccountDetail,
}) => {
  const [accountExtend, setAccountExtend] = useState({}); //认证信息
  const [codeVisible, setCodeVisible] = useState(false); //手机验证码弹窗visible
  const [previewVisible, setPreviewVisible] = useState(false); //查看图片弹窗的visible
  const [previewImage, setPreviewImage] = useState(''); //查看身份证的图片预览
  const [previewImageKey, setPreviewImageKey] = useState(1); //查看身份证的图片预览
  const [authenticationVisible, setAuthenticationVisible] = useState(false); // 认证的visible
  const [isUpgrade, setIsUpgrade] = useState(false); //是否是升级
  const [step, setStep] = useState(1); //步骤
  const [type, setType] = useState(2); //企业类型
  const [bindVisible, setBindVisible] = useState(false); //绑定银行卡
  const [tipsMsg, setTipsMsg] = useState(null); //温馨提示弹窗
  const [verification, setVerification] = useState(true); //判断是否是第一次验证(是否需要重新发送验证码)
  const [loading, setLoading] = useState(false);

  const {
    userType,
    hasOpenAccount,
    hasOpenClassIIAccount,
    enterpriseAuthModifyState,
  } = userAccountType;

  const stageData = useRef({
    cityCode: undefined,
    countyCode: undefined,
    panCardUploadSn: undefined, //平安影像审核编码
    provinceCode: undefined,
  });

  useEffect(() => {
    if (visible) {
      getAuthenticationInfo();
    }
  }, [visible]);

  //获取认证信息
  const getAuthenticationInfo = async () => {
    setLoading(true);
    const { data = {}, success } = await getAttestation();
    if (success) {
      setAccountExtend(data);
    }
    setLoading(false);
  };

  //点击去开户
  const openAccount = () => {
    if (userType == 1) {
      //大用户
      enterpriseOnOk();
    } else if (userType == 2) {
      //普通老用户
      personaloOnOk();
    } else {
      //新用户
      if (accountExtend?.accountType == 1) {
        //个人认证
        if(UpgradeEnterprise) {
            message.info('您已开通二类户，可以操作企业认证升级企业账户');
        } else {
            personaloOnOk();
        }
      } else {
        //企业认证
        enterpriseOnOk();
      }
    }
  };

  //企业开户的提交
  const enterpriseOnOk = () => {
    setStep(2);
  };

  //开见证宝(大用户开户)
  const WitnessTreasureonOk = async () => {
    setTipsMsg({ type: 2 });
    const { data, success, msg } = await userOpenAccount({
      accountType: type,
    });
    if (success) {
      message.success('开通成功');
      setTipsMsg(null);
      handleOk();
    } else {
      setTipsMsg({
        type: 4,
        // key: type,
        reason: msg,
      });
    }
  };

  //银行验证资料(个人认证开二类户)
  const personaloOnOk = async () => {
    setTipsMsg({ type: 2 });
    const { data, success } = await bankValidate();
    if (success) {
      stageData.current = { ...stageData.current, ...(data || {}) };
      setBindVisible(true);
    }
    setTipsMsg(null);
  };

  //渲染底部按钮
  const renderFooter = useMemo(() => {
    if (isOpen) {
      //开户流程详情
      if (step == 2) {
        return (
          <>
            <Button key="cancel" onClick={() => setStep(1)}>
              上一步
            </Button>
            <Button
              key="next"
              onClick={() => WitnessTreasureonOk()}
              type="primary"
            >
              下一步
            </Button>
          </>
        );
      } else {
        return (
          <>
            <Button
              shape="round"
              className="newRoundBtn2"
              key="cancel"
              onClick={handleCancel}
            >
              取消
            </Button>
            <Button
              key="next"
              shape="round"
              onClick={openAccount}
              type="primary"
              size="middle"
            >
              {accountExtend?.accountType == 1 ? '确认' : '提交'}
            </Button>
          </>
        );
      }
    } else {
      //非开户详情
      return (
        <>
          <Button shape="round" className="newRoundBtn2" onClick={handleCancel}>
            关闭
          </Button>
        </>
      );
    }
  }, [isOpen, step, accountExtend, type]);

  //渲染认证详情数据
  const renderContent = useMemo(() => {
    if (accountExtend.accountType == 1) {
      return (
        <div>
          <div className={styles.detailItem}>
            <span>姓名： </span>
            <span>{accountExtend?.userName}</span>
          </div>
          <div className={styles.detailItem}>
            <span>性别： </span>
            <span>{accountExtend?.sex}</span>
          </div>
          <div className={styles.detailItem}>
            <span>民族： </span>
            <span>{accountExtend?.nation}</span>
          </div>
          <div className={styles.detailItem}>
            <span>身份证号： </span>
            <span>{IdCardDesensitization(accountExtend.idCard)}</span>
          </div>
          <div className={styles.detailItem}>
            <span>有效期： </span>
            <span>{`${accountExtend?.issueDate} - ${accountExtend?.expiryDate}`}</span>
          </div>
          <div className={styles.detailItem}>
            <span>职业： </span>
            <span>{`${accountExtend?.occupationName} ${
              accountExtend.occupation ? `（${accountExtend.occupation}）` : ''
            }`}</span>
          </div>
          <div className={styles.detailItem}>
            <span>常住地址： </span>
            <span>{`${accountExtend?.provinceName}${accountExtend?.cityName}${accountExtend?.countyName}**********`}</span>
          </div>
        </div>
      );
    } else {
      return (
        <div>
          <div className={styles.detailItem}>
            <span>营业执照名称： </span>
            <span>{accountExtend?.licenseName}</span>
          </div>
          <div className={styles.detailItem}>
            <span>社会统一信用代码： </span>
            <span>
              {accountExtend.socialCreditCode
                ? accountExtend.socialCreditCode.substr(0, 2) +
                  '****' +
                  accountExtend.socialCreditCode.substr(
                    accountExtend.socialCreditCode.length - 2
                  )
                : ''}
            </span>
          </div>
          <div className={styles.detailItem}>
            <span>法人姓名： </span>
            <span>{accountExtend?.userName}</span>
          </div>
          <div className={styles.detailItem}>
            <span>性别： </span>
            <span>{accountExtend?.sex}</span>
          </div>
          <div className={styles.detailItem}>
            <span>民族： </span>
            <span>{accountExtend?.nation}</span>
          </div>
          <div className={styles.detailItem}>
            <span>身份证号： </span>
            <span>{IdCardDesensitization(accountExtend.idCard)}</span>
          </div>
          <div className={styles.detailItem}>
            <span>有效期： </span>
            <span>{`${accountExtend?.issueDate} - ${accountExtend?.expiryDate}`}</span>
          </div>
          <div className={styles.detailItem}>
            <span>职业： </span>
            <span>{`${accountExtend?.occupationName} ${
              accountExtend.occupation ? `（${accountExtend.occupation}）` : ''
            }`}</span>
          </div>
          <div className={styles.detailItem}>
            <span>常住地址： </span>
            <span>{`${accountExtend?.provinceName}${accountExtend?.cityName}${accountExtend?.countyName}**********`}</span>
          </div>
        </div>
      );
    }
  }, [accountExtend]);

  //修改认证信息是否展示
  const editButton = useMemo(() => {
    if (accountExtend.accountType == 1) {
      //个人认证
      if (!hasOpenClassIIAccount) {
        //未开通二类户
        return (
          <Button
            className="newColorRoundBtn"
            shape="round"
            onClick={() => handleEdit()}
          >
            修改认证信息
          </Button>
        );
      }
    } else {
      //企业认证
      if (!hasOpenAccount) {
        //没有通见证宝可以修改企业认证
        return (
          <Button
            className="newColorRoundBtn"
            shape="round"
            onClick={() => handleEdit()}
          >
            修改认证信息
          </Button>
        );
      } else {
        //开通了见证宝需要根据见证宝信息判断是否可以修改
        if (enterpriseAuthModifyState == 1) {
          return (
            <Button
              className="newColorRoundBtn"
              shape="round"
              onClick={() => handleEdit()}
            >
              修改认证信息
            </Button>
          );
        }
      }
    }
  }, [accountExtend, userType, userAccountType]);

  //渲染图片展示
  const renderImg = (src, title) => {
    return (
      <div className={styles.imgBox}>
        <CommonQinnvImgsLoad
          key={src}
          onPreview={() => {
            handleView(src);
          }}
          noRemove={true}
          className={title ? 'rectangleSmallBlur' : 'rectangleLargeBlur'}
          img={src}
        />
        <div>{title ? title : ''}</div>
      </div>
    );
  };

  //点击查看照片
  const handleView = (url) => {
    if (verification) {
      setCodeVisible(true);
    } else {
      setPreviewVisible(true);
    }
    setPreviewImageKey(previewImageKey + 1);
    setPreviewImage(url);
  };

  //点击修改认证
  const handleEdit = () => {
    setAuthenticationVisible(true);
    setIsUpgrade(false);
  };

  //点击升级认证
  const handleUpgrade = () => {
    setAuthenticationVisible(true);
    setIsUpgrade(true);
  };

  //修改认证/升级企业认证
  const AddAuthenticationProps = {
    visible: authenticationVisible,
    accountExtend,
    userAccountType,
    isUpgrade,
    handleCancel() {
      setAuthenticationVisible(false);
    },
    handleOk() {
      setAuthenticationVisible(false);
      getAuthenticationInfo();
      handUpdateAccountDetail();
    },
  };

  //输入验证码弹窗
  const CheckCellPhoneCodeModalProps = {
    visible: codeVisible,
    handleCancel() {
      setCodeVisible(false);
    },
    handleOk(val) {
      if (val) {
        setCodeVisible(false);
        // setPreviewImage(val);
        setPreviewVisible(true);
        setVerification(false);
      }
    },
  };

  //新绑卡modal
  const bindCardProps = {
    params: stageData,
    accountExtend,
    handleOk() {
      handUpdataData();
    },
    handleCancel() {
      setBindVisible(false);
    },
    handleAllCancel() {
      //关闭认证详情弹窗
      handleCancel();
    },
  };

  //温馨提示modal
  const tipsModalProps = {
    tipsMsg,
    handleOk() {
      setStep(1);
      setTipsMsg(null);
    },
  };

  return (
    <CommonModal
      title={`${typeMap[accountExtend?.accountType]}认证信息`}
      visible={visible}
      onCancel={handleCancel}
      forceRender={false}
      width={step == 2 ? 400 : 550}
      footer={renderFooter}
      className={step == 2 ? '' : styles.addAuthenticationBox}
    >
      {step == 1 ? (
        <>
          <div className={styles.detailBox}>
            {isOpen ? (
              <Alert message="请检查实名认证资料是否为开户所需账户资料，确保用户信息和有效期都准确，将提交银行进行验证" />
            ) : (
              ''
            )}
            <div className={styles.boxLeft}>
              <div className={styles.weightText}>
                <div className={styles.boxHeader}>
                  <div>{editButton}</div>
                  <div style={{ marginLeft: '12px' }}>
                    {accountExtend?.accountType == 1 && (
                      <Button
                        className="newColorRoundBtn"
                        shape="round"
                        onClick={() => handleUpgrade()}
                      >
                        升级为企业认证
                      </Button>
                    )}
                  </div>
                </div>
                <div className={styles.attestationTitle}>{`${
                  typeMap[accountExtend?.accountType]
                }认证信息`}</div>
                <div className={styles.boxInfo}>{renderContent}</div>
              </div>

              <div className={styles.leftBottom}>
                {accountExtend?.accountType != 1 && (
                  <div style={{ marginBottom: '16px' }}>
                    <div className={styles.attestationTitle}>营业执照：</div>
                    {/* {isOpen ? ( */}
                    <div
                      style={{
                        marginLeft: '40px',
                      }}
                    >
                      {renderImg(accountExtend?.businessLicenseUrlJM)}
                    </div>
                  </div>
                )}

                <div>
                  <div className={styles.attestationTitle}>法人身份证：</div>
                  <div>
                    <div
                      style={{
                        display: 'flex',
                        justifyContent: 'flex-end',
                      }}
                    >
                      {renderImg(
                        accountExtend?.idCardFrontUrlJM,
                        '身份证人像面'
                      )}
                      {renderImg(
                        accountExtend?.idCardBackUrlJM,
                        '身份证国徽面'
                      )}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </>
      ) : (
        <>
          <div style={{ paddingLeft: '40px', marginTop: '4px' }}>
            <Radio.Group onChange={(e) => setType(e.target.value)} value={type}>
              <Radio value={2}>个体工商户</Radio>
              <p style={{ height: '6px' }}></p>
              <Radio value={3}>企业户</Radio>
            </Radio.Group>
          </div>
        </>
      )}
      {/* 短信验证码弹窗 */}
      <CheckCellPhoneCodeModal {...CheckCellPhoneCodeModalProps} />
      {/* 修改/升级认证信息 */}
      {authenticationVisible && <AddAuthentication {...AddAuthenticationProps} />}
      <CommonModal
        visible={previewVisible}
        title="图片预览"
        footer={null}
        onCancel={() => setPreviewVisible(false)}
      >
        <img
          key={previewImageKey}
          alt=""
          style={{ width: '100%' }}
          src={previewImage}
        />
      </CommonModal>
      {/* 新绑卡 */}
      {bindVisible && <NewBindCardModal {...bindCardProps} />}
      {/* 温馨提示 */}
      {tipsMsg && <ComfortableTipsModal {...tipsModalProps} />}
      <CommonLoading loading={loading} />
    </CommonModal>
  );
};

export default AttestationDetail;
